﻿using System;
using System.Collections.Generic;
using System.Text;
using FeedDotNet.Common;
using System.Xml;
using System.IO;

namespace ConsoleApplication
{
    static class FeedDotNetExporter
    {
        public static String ExportFeed(Feed feed)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                XmlTextWriter writer = new XmlTextWriter(ms, Encoding.ASCII);
                writer.WriteStartDocument();
                WriteRss2Header(writer);

                writer.WriteStartElement("channel");
                writer.WriteElementString("title", feed.Title);
                writer.WriteElementString("link", "http://code.google.com/p/googlaru");
                writer.WriteElementString("description", feed.Description);
                if (feed.Published.HasValue)
                    writer.WriteElementString("published", feed.Published.Value.ToString());
                writer.WriteElementString("language", "en-us");
                foreach (FeedItem item in feed.Items)
                {
                    ExportItem(item, writer);
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();

                writer.Flush();
                return Encoding.ASCII.GetString(ms.ToArray());
            }
        }

        private static void ExportItem(FeedItem item, XmlTextWriter writer)
        {
            if (item == null)
                return;

            writer.WriteStartElement("item");
            if (item.Title != null)
                writer.WriteElementString("title", item.Title);
            if (item.Source != null)
                writer.WriteElementString("link", item.Source.Uri.ToString());
            if (item.Summary != null)
                writer.WriteElementString("description", item.Content);
            if (item.Published.HasValue)
                writer.WriteElementString("pubDate", item.Published.Value.ToString());
            if (item.Guid != null)
                writer.WriteElementString("guid", item.Guid);

            foreach (Enclosure en in item.Enclosures)
            {
                if (string.IsNullOrEmpty(en.Uri) || string.IsNullOrEmpty(en.Title))
                    continue;

                writer.WriteStartElement("enclosure");
                writer.WriteAttributeString("url", en.Uri);
                writer.WriteAttributeString("length", en.Length.ToString());
                writer.WriteAttributeString("type", en.Type);
                writer.WriteEndElement();

            }

            writer.WriteEndElement();
        }

        private static void WriteRss2Header(XmlTextWriter writer)
        {
            writer.WriteStartElement("rss");
            writer.WriteAttributeString("version", "2.0");
        }
    }
}
